package com.service.serviceImpl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.config.CacheKeyManager;
import com.mapper.VideoMapper;
import com.model.Video;
import com.service.VideoService;
import com.utils.BaseCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 视频服务实现接口
 */
@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {

    @Autowired
    private BaseCache baseCache;


    @Override
    public List<Video> listVideo() {
        try{
            /*
            每个用户的频繁操作功能，存入内存提高性能
             */
            Object cacheObj =  baseCache.getTenMinuteCache().get(CacheKeyManager.INDEX_VIDEL_LIST,()->{

                List<Video> videoList =this.list();
                baseCache.getTenMinuteCache().put(CacheKeyManager.INDEX_VIDEL_LIST,videoList);
                return videoList;

            });

            if(cacheObj instanceof List){
                List<Video> videoList = (List<Video>)cacheObj;
                return videoList;
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 由于是多表查询，多次往数据库拿影响性能，因此存入内存
     * @param videoId
     * @return
     */
    @Override
    public Video findDetailById(int videoId) {
        //单独构建一个缓存key，每个视频的key是不一样的
        String videoCacheKey = String.format(CacheKeyManager.VIDEO_DETAIL,videoId);
        try{
            Object obj=baseCache.getOneHourCache().get(videoCacheKey,()->{

                //往数据库拿数据
                Video video=baseMapper.findDetailById(videoId);
                //存入内存
                baseCache.getOneHourCache().put(videoCacheKey,video);
                return video;

            });

            //内存拿到的数据判断返回
            if(obj instanceof Video){
                return (Video)obj;
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
